package org.sun.sunshine.io.nio;

import java.io.IOException;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NioClient {
    public static void main(String[] args) throws IOException {
        //nio client
        Selector selector=Selector.open();
        SocketChannel socketChannel=SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new java.net.InetSocketAddress("127.0.0.1",8080));
        socketChannel.register(selector, SelectionKey.OP_CONNECT);

        while (true) {
            // 选择键
            selector.select();
            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            Iterator<SelectionKey> iter = selectedKeys.iterator();
            while (iter.hasNext()) {
                SelectionKey key = iter.next();
                iter.remove();
                if (key.isConnectable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    if (channel.finishConnect()) {
                        System.out.println("Connected to server");
                        channel.register(selector, SelectionKey.OP_WRITE);
                        // 发送数据到服务器
                        ByteBuffer buffer = ByteBuffer.wrap("hello".getBytes());
                        channel.write(buffer);
                        System.out.println("Sent to server:");
                    } else {
                        System.out.println("Failed to connect to server");
                    }
                }
            }
        }

    }
}
